
import 'package:flutter/material.dart';
import 'package:get/get.dart';

HistoryRouteObserver routeHistoryObserver = HistoryRouteObserver();

typedef HistoryRouteListener = void Function(List<Route<dynamic>> history);

// typedef CurrentRouteListener = void Function(Route<dynamic> currentRpute);

class HistoryRouteObserver extends RouteObserver<PageRoute> {
  List<Route<dynamic>> history = <Route<dynamic>>[];

  List<Route<dynamic>> historyPath = <Route<dynamic>>[];

  List<HistoryRouteListener> listeners = [];

  addHistoryRouteListener(HistoryRouteListener listener) {
    listeners.add(listener);
  }

  removeHistoryRouteListener(HistoryRouteListener listener) {
    listeners.remove(listener);
  }

  // List<CurrentRouteListener> curretListeners = [];
  //
  // addCurrentRouteListener(CurrentRouteListener listener) {
  //   curretListeners.add(listener);
  // }
  //
  // removeCurrentRouteListener(CurrentRouteListener listener) {
  //   curretListeners.remove(listener);
  // }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    history.remove(route);
    if (history.length == 1) {}
    if (listeners.isNotEmpty) {
      for (var element in listeners) {
        element.call(history);
      }
    }
    // if (curretListeners.isNotEmpty) {
    //   for (var element in curretListeners) {
    //     element.call(route);
    //   }
    // }
  }

  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    history.add(route);
    historyPath.add(route);
    if (listeners.isNotEmpty) {
      for (var element in listeners) {
        element.call(history);
      }
    }
  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    super.didRemove(route, previousRoute);
    history.remove(route);
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    if (oldRoute != null) {
      history.remove(oldRoute);
    }
    if (newRoute != null) {
      history.add(newRoute);
    }
  }

  ///移除指定的页面,一次
  void removeName(String name) {
    var route = getRouteByName(name);
    if (route != null) {
      if (history.last == route) {
        //移除当前页面，直接返回
        Get.back();
      } else {
        Get.removeRoute(route);
      }
    }
  }

  Route? getRouteByName(String name) {
    var index = history.lastIndexWhere((element) => element.settings.name == name);
    if (index != -1) {
      return history[index];
    }
    return null;
  }
}
